package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"play/cache"
	"play/models"
	"strconv"
)

type PlayController struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *PlayController) Add() {
	title := c.GetString("title")
	auto := c.GetString("auto")
	price, _ := c.GetFloat("price")

	if title == "" || auto == "" || price == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "数据不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	play := models.Play{
		Title: title,
		Auto:  auto,
		Price: price,
	}

	add := "add" + strconv.Itoa(int(play.ID))
	caheJson, _ := json.Marshal(&play)
	cache.Rdb.Set(cache.Ctx, add, caheJson, 0)

	err := models.DB.Create(&play).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}

func (c *PlayController) List() {
	var play []models.Play

	list := "list"
	key, _ := cache.Rdb.Get(cache.Ctx, list).Result()
	if key == "" {
		models.DB.Find(&play)

		cacheJson, _ := json.Marshal(play)
		cache.Rdb.Set(cache.Ctx, list, cacheJson, 0)
	} else {
		json.Unmarshal([]byte(key), &play)
	}

	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: play,
	}
	c.ServeJSON()
	return
}

func (c *PlayController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	auto := c.GetString("auto")
	price, _ := c.GetFloat("price")

	if title == "" || auto == "" || price == 0 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "数据不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	play := models.Play{
		Title: title,
		Auto:  auto,
		Price: price,
	}

	err := models.DB.Where("id=?", id).Create(&play).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}

func (c *PlayController) Del() {
	id, _ := c.GetInt("id")
	del := "add" + strconv.Itoa(id)
	caheJson, _ := json.Marshal(&models.Play{})
	cache.Rdb.Set(cache.Ctx, del, caheJson, 0)

	err := models.DB.Delete(&models.Play{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
